// components/recipe-status/index.js
import {
  request
} from '../../api/index'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    status: {
      type: String,
      value: '',
      observer: 'setDataSource'
    },
    recipe: {
      type: Object,
      value: {}
    },
    root: {
      type: Boolean,
      observer: 'check'
    },
    show: {
      type: Boolean,
      observer: 'check'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    value: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    setDataSource(value) {
      this.setData({
        value
      })
    },
    check(val) {
      this.setData({
        isRoot: getApp().globalData.root
      })
    },
    onChange() {
      const value = this.data.value;
      const root = getApp().globalData.root;

      if ((!root && value !== 'TO_BE_ANNOUNCED') || (!root && value === 'CHECK')) {
        return
      }
      let target, text;
      switch (value) {
        case 'TO_BE_ANNOUNCED':
          target = 'ANNOUNCED';
          text = root ? '已发布' : '审核中';
          break;
        case 'ANNOUNCED':
          target = 'STOP';
          text = '已挂起';
          break;
        case 'CHECK':
          target = 'ANNOUNCED';
          text = '已发布';
          break;
        case 'STOP':
          target = 'ANNOUNCED';
          text = '已发布';
          break;
        default:
          wx.showToast({
            title: '修改失败',
            icon: 'error'
          })
          break;
      }
      if (target) {
        const _this = this;
        wx.showModal({
          title: '提示',
          content: `配方状态将被修改为： ${text}`,
          success(res) {
            if (res.confirm) {
              if (target === 'STOP' && root === false) {
                wx.showModal({
                  title: '操作失败',
                  content: '“挂起” 只能由管理员操作',
                  showCancel: false
                })
                return
              }
              request.recipeUpdateStatus({
                id: _this.properties.recipe?.id,
                status: target
              }, () => {
                _this.setData({
                  value: target
                })
                _this.triggerEvent('change', target === 'ANNOUNCED' ? root ? target : 'CHECK' : target);
              })
            }
          }
        })
      }
    }
  }
})